package controller;

import DBCP.MyDBCP;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import user.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@Controller
@RequestMapping("user")
public class UserController extends BaseController{
    @RequestMapping("SignIn")
    public String signIn(){
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String selectSql = "select * from db_user.user where username = ? and password = ?";
        Connection con = MyDBCP.getConnection();
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = con.prepareStatement(selectSql);
            ps.setString(1,username);
            ps.setString(2,password);
            rs = ps.executeQuery();
            if (rs.next()){
                String user_username = rs.getString("username");
                String user_password = rs.getString("password");
                User user = new User(user_username,user_password);
                session.setAttribute("user",user);
                return "redirect:/user.jsp";
            }else {
                session.setAttribute("error","check your username and password!!");
                return "redirect:/index.jsp";
            }

        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(rs,ps,con);
        }
    }
    @RequestMapping("SignUp")
    public String signUp(){
        //todo
        return null;
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String insertSql = "insert into db_user.user values (null,?,?)";
        Connection con = MyDBCP.getConnection();
        PreparedStatement ps = null;
        try {
            ps = con.prepareStatement(insertSql);
            ps.setString(1,username);
            ps.setString(2,password);
            ps.executeUpdate();
            session.setAttribute("message","insert successfully!!");
            return "redirect:/index.jsp";
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            MyDBCP.close(null,ps,con);
        }
    }
}